package com.website.common.util;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * web工具
 *
 * @author zhangsw
 */
public class WebUtil {

	/**
	 * 获取客户端机器IP地址
	 *
	 * @param request
	 * @return String
	 * @author zhangsw
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("WL-Proxy-Client-IP");
					if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
						ip = request.getHeader("HTTP_CLIENT_IP");
						if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
							ip = request.getHeader("HTTP_X_FORWARDED_FOR");
							if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
								ip = request.getRemoteAddr();
							}
						}
					}
				}
			}
		} else {
			int index = ip.indexOf(",");
			return index < 0 ? ip : ip.substring(0, index);
		}
		return ip;
	}

	/**
	 * 是否是Ajax请求
	 * @param request 请求
	 * @return boolean
	 */
	public static boolean isAjax(ServletRequest request){
		return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"));
	}
}
